package com.payment.paymentmanagersystem.controller;

import com.payment.paymentmanagersystem.dal.UserDAL;
import com.payment.paymentmanagersystem.model.UserInfo;
import com.payment.paymentmanagersystem.unit.Response;
import com.payment.paymentmanagersystem.unit.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 用户功能相关API
 *
 * @author 李耀华
 * @date 2023年6月14日
 */
@RestController
public class UserController {
    @Autowired
    UserDAL userDAL;

    /**
     * 用户注册功能请求
     *
     */
    @CrossOrigin
    @RequestMapping(value = "/regUser", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response regUser(@RequestBody UserInfo user){
        if(userDAL.isLoginNameExits(user)){
            return new Response(403,"邮箱已经存在",null);
        }
        if(userDAL.isLoginNameExits(user)){
            return new Response(403,"用户名已经存在",null);
        }
        if(userDAL.RegisterUser(user)){
            return new Response(200,"注册成功",null);
        }else{
            return new Response(403,"注册失败",null);
        }
    }

    /**
     * 用户验证激活
     *
     */
    @CrossOrigin
    @RequestMapping(value = "/activeUser/{code}", method = RequestMethod.GET, produces = "application/json; utf-8")
    public Response activeUser(@PathVariable("code") String activeCode){
        UserInfo user = new UserInfo();
        user.setAlive_code(activeCode);
        return new Response(200,"激活用户",userDAL.activeEmail(user));
    }

    /**
     * 用户登录
     */
    @CrossOrigin
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response loginUser(@RequestBody UserInfo user){
        UserInfo loginUser = userDAL.validateUser(user);
        if(loginUser!=null){
            String token = TokenUtils.sign(user);
            HashMap<String, Object> hs = new HashMap<>();
            hs.put("token", token);
            hs.put("user",loginUser);
            return new Response(200,"登录成功",hs);
        }else{
            return new Response(403,"登录失败",null);
        }
    }

    /**
     * 查询个人余额
     */
    @CrossOrigin
    @RequestMapping(value = "/getBlance", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response getBlanceByUser(@RequestBody UserInfo user){
        return new Response(200,"查询余额",userDAL.getBlanceByUserId(user));
    }

    /**
     * 查询个人支付信息
     *
     */
    @CrossOrigin
    @RequestMapping(value = "/getPayinfo", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response getPayinfo(@RequestBody UserInfo user){
        return new Response(200,"查询付款信息",userDAL.getPayInfoListByUserId(user));
    }
}
